package control

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func HelloHandler(c *gin.Context) {
	//time.Sleep(3*time.Second)
	// gin.H封装了生成json数据的工具
	c.JSON(200, gin.H{
		"msg": "<h1>hello world</h1>",
	})  //{"msg":"\u003ch1\u003ehello world\u003c/h1\u003e"}

	c.PureJSON(200, gin.H{
		"msg": "<h1>hello world</h1>",
	})  //{"msg":"<h1>hello world</h1>"}
}

func GetUrlQueryHandler(c *gin.Context) {
	p1 := c.Query("u")             //没有该参数返回空
	p2 := c.DefaultQuery("n", "1") //没有该参数，则使用默认值"1"
	c.JSON(200, gin.H{
		"p1": p1,
		"p2": p2,
	})
}

func GetUrlParamHandler(c *gin.Context) {
	//使用/p/id/name url
	p1 := c.Param("id")
	p2 := c.Param("name")
	c.JSON(200, gin.H{
		"p1": p1,
		"p2": p2,
	})
}

func GetFormParamHandler(c *gin.Context) {
	//使用/p/id/name url
	p1 := c.PostForm("id")
	p2 := c.PostForm("name")
	c.JSON(200, gin.H{
		"p1": p1,
		"p2": p2,
	})
}



func UploadFileHandler(c *gin.Context) {
	//限制文件大小和格式
	//_, headers, err := c.Request.FormFile("file")
	//if err != nil {
	//	fmt.Printf("Error when try to get file: %v", err)
	//}
	////headers.Size 获取文件大小
	//if headers.Size > 1024*1024*2 {
	//	fmt.Println("文件太大了")
	//	return
	//}
	////headers.Header.Get("Content-Type")获取上传文件的类型
	//if headers.Header.Get("Content-Type") != "image/png" {
	//	fmt.Println("只允许上传png图片")
	//	return
	//}
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": err.Error(),
		})
		return
	}
	dst := fmt.Sprintf("./upload/%s", file.Filename)
	err = c.SaveUploadedFile(file, dst)
	if err == nil{
		c.JSON(http.StatusOK, gin.H{
			"msg": "upload successed",
		})
	}else {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "upload failed："+ err.Error(),
		})
	}
}

func MultiFileHandler(c *gin.Context) {
	form, err := c.MultipartForm()
	if err!=nil{
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "MultipartForm error:"+err.Error(),
		})
		return
	}
	var errFile error
	files := form.File["file"]
	for _, file := range files {
		dst := fmt.Sprintf("./upload/%s", file.Filename)
		errFile = c.SaveUploadedFile(file, dst)
	}
	if errFile==nil{
		c.JSON(http.StatusOK, gin.H{
			"msg": "upload successed",
		})
	}else {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "upload failed："+ errFile.Error(),
		})
	}

}

func Login(c *gin.Context) {
	name := c.DefaultQuery("name", "小明")
	c.String(200, fmt.Sprintf("hello %s\n", name))
}

func Submit(c *gin.Context) {
	name := c.DefaultQuery("name", "小花")
	c.String(200, fmt.Sprintf("hello %s\n", name))
}

func DoGet(c *gin.Context) {

	name := c.DefaultQuery("name", "小强")
	c.String(200, fmt.Sprintf("hello %s\n", name))

}

